<?php
class MemberModel extends CommonModel {
    public function __construct(){
        parent::__construct();
    }

    
    //获取用户列表数据
    public function queryMemberList($p  , $where = array() ,$must_field , $default_field ,$all_field ){
       
        $per_page = $where['pageSize'] ;
        if($p <=0 ){
            $p = 1 ;
        }
        $getWhereData  = $this->get_where($where);
        $getwhere = $getWhereData['getwhere'];;
        $myfield = $getWhereData['myfield'];
        $orderby = $getWhereData['orderby'];
        $field = '' ;
        $str_head = array() ; //表格的头部数组
        $return_field_data = $this->get_return_field($must_field , $default_field ,$all_field,$where['show_field']);
        $str_head = $return_field_data['str_head'];
        $field = $return_field_data['field'];
        $str_head['action_do']="操作";
        import('Library.Page' , APP_PATH);
        $limit = ($p-1)*$per_page;
        $limit.=",{$per_page}";
       
        $sql_count = "select count(*) as c from ".C("DB_PREFIX")."member as a   {$getwhere}" ;
        $count_data = M()->query($sql_count);
        $total = $count_data[0]['c'];

        $page = new Page($total,$per_page);
        $page_string =  $page->show();
        
        $sql = "select $field  from ".C("DB_PREFIX")."member as a {$getwhere} order by {$myfield} {$orderby}  limit {$limit}" ;
    	//echo $sql;
        $list = M()->query($sql);
        $fieldData = explode("," , $field);
        $sex_data = array(
        		0=>'保密',
        		1=>'男',
        		2=>'女'
        );
        if($list){
            foreach($list AS $k => $v ){
            	if(in_array("a.regdate", $fieldData)){
            		$list[$k]['regdate'] = date("Y-m-d H:i:s" , $v['regdate']) ;
            	}
                $list[$k]['action_do'] = "<a href=\"javascript:void(0)\" onclick=\"edit('{$v['uid']}')\">编辑</a>" ;
                if(in_array("a.sex", $fieldData)){
                	$list[$k]['sex'] = $sex_data[$v['sex']];
                }
                $list[$k]['uid'] = $v['uid']."加密值:<font color='red'>".auth_code($v['uid'],"ENCODE")."</font>";
                if(in_array("a.status", $fieldData)){
                	$list[$k]['status'] = ($v['status'] == 0 )?"<font color='red'>禁用</font>":"正常";
                }
                if(in_array("a.pic", $fieldData)){
                	$picUrl = C("upload_domain")."/User/{$v['pic']}";
                	$list[$k]['pic'] = ($v['pic'] != '' )?"<img src='{$picUrl}' width='80' height='80'>":'无图像';
                }
                if(in_array("a.money", $fieldData)){
                	$list[$k]['money'] = "￥{$v['money']}";
                }
                if(in_array("a.expire", $fieldData)){
                	$expire='';
                	if($v['expire'] > 0 ){
                		if(time() > $v['expire']){
                			$expire="<font color='red'>已经过期</font>";
                		}else{
                			$expire = "<font color='green'>".date("Y-m-d H:i:s" , $v['expire']) ."</font>";
                		}
                	}else{
                		$expire="永不过期";
                	}
                	$list[$k]['expire'] = $expire;
                }
            }
        }
        $data = array(
        		'list'=>array('list'=>$list , 'head'=>$str_head  , 'total'=>$total)  ,
        		'page_string'=>$page_string
        );
        return $data ;
    }
    //根据传递过来的参数获取model的搜素语句,返回查询条件 和排序字段还有按照什么进行排序
    //return array
    public function get_where($where = array() ){
        $getwhere = " where 1 = 1 " ;
        $condition = intval(isset($where['condition'])?$where['condition']:1);
        $condition  = in_array($condition,array(1,2))?$condition:1;
        if(isset($where['username']) && $where['username']){
            $username = $where['username'] ;
            $array_condition_search  = array(
                    1=>" LIKE '%{$username}%'", //模糊搜索
                    2=>"= '{$username}'"
            );
            $getwhere .= " AND a.username {$array_condition_search[$condition]} " ; 
        }
        if(isset($where['phone']) && $where['phone']){
            $phone = $where['phone'];
            $getwhere.=" AND a.phone = '{$phone}' " ;
        }
        if(isset($where['uname']) &&  $where['uname'] ){
            $getwhere.=" AND a.uname like '%{$where['uname']}%' ";
        }
        if(isset($where['uid']) &&  $where['uid']>0 ){
            $getwhere.=" AND a.uid = '{$where['uid']}' ";
        }
        if( in_array($where['status'] , array('1', '0' ) ) ){
            $getwhere.=" AND a.status = '{$where['status']}' ";
        }
        if( in_array($where['sex'] , array('1', '2' ) ) ){
            $getwhere.=" AND a.sex = '{$where['sex']}' ";
        }
        $myfield = $where['field'] ; 
        $orderby = $where['orderby'] ;
        if(!in_array(strtolower($orderby), array('asc' , 'desc' ))){
            $orderby = "asc" ; 
        }
        return array('getwhere'=>$getwhere , 'myfield'=>$myfield , 'orderby'=>$orderby  );
    }
    //获取mysql查询的字段 select 字段,和表格的头部
    //return array
    public function get_return_field($must_field , $default_field ,$all_field,$show_field){
        $field = '' ;
        $str_head = array() ; //表格的头部数组
        $fieldData = getField($must_field , $default_field ,$all_field,$show_field );
        $field = $fieldData['field'];
        $str_head = getHead($field,$must_field , $default_field ,$all_field);
        return array('field'=>$field , 'str_head'=>$str_head );
    }
    //导出
    public function export($p  , $where = array() ,$must_field , $default_field ,$all_field ){
        $per_page = $where['pageSize'] ;
        if($p <=0 ){
            $p = 1 ;
        }
        $getWhereData  = $this->get_where($where);
        $getwhere = $getWhereData['getwhere'];;
        $myfield = $getWhereData['myfield'];
        $orderby = $getWhereData['orderby'];
        $field = '' ;
        $str_head = array() ; //表格的头部数组
        $return_field_data = $this->get_return_field($must_field , $default_field ,$all_field,$where['show_field']);
        $str_head = $return_field_data['str_head'];
        $field = $return_field_data['field'];
        $limit = ($p-1)*$per_page;
        $limit.=",{$per_page}";
        $sql = "select $field  from ".C("DB_PREFIX")."member as a {$getwhere} order by {$myfield} {$orderby}  limit {$limit}" ;
        $list = M()->query($sql);
        $fieldData = explode("," , $field);
        $sex_data = array(
                0=>'保密',
                1=>'男',
                2=>'女'
        );
        $exportData = array();
        $exportData[1] = array_values($str_head);
        $index = 1 ;
        if($list){
            foreach($list AS $k => $v ){
            	$index++;
                if(in_array("a.regdate", $fieldData)){
                    $v['regdate'] = date("Y-m-d H:i:s" , $v['regdate']) ;
                }
               
                if(in_array("a.sex", $fieldData)){
                    $v['sex'] = $sex_data[$v['sex']];
                }
               
                if(in_array("a.status", $fieldData)){
                    $v['status'] = ($v['status'] == 0 )?"禁用":"正常";
                }
               
                if(in_array("a.money", $fieldData)){
                    $v['money'] = "￥{$v['money']}";
                }
                if(in_array("a.expire", $fieldData)){
                    $expire='';
                    if($v['expire'] > 0 ){
                        if(time() > $v['expire']){
                            $expire="已经过期";
                        }else{
                            $expire = date("Y-m-d H:i:s" , $v['expire']) ;
                        }
                    }else{
                        $expire="永不过期";
                    }
                    $v['expire'] = $expire;
                }
                $exportData[$index]=$v;
            }
        }

        import('Library.Excel' , APP_PATH);
        $xls = new Excel('UTF-8' , FALSE  ,'用户信息导出');
        $xls->addArray($exportData);
        $xls->generateXML("用户信息导出");
    }
    //根据ID查询信息
    public function getMemberDataById($id){
        return M("Member")->where("uid='{$id}'")->find();
    }
    
    //修改信息
    function editMember(){
        
        if($_POST['edit_pwd_ok'] == 1 ){
            if($_POST['info']['passwd'] == '' || utf8_str($_POST['info']['passwd']) != 1 ){
                return array('status'=> 0 , 'message'=> '密码不能为空必须是英文' );
            }else{
              $_POST['info']['passwd'] = md5(trim($_POST['info']['passwd']));  
            }
        }else{
        	unset($_POST['info']['passwd']);
        }
        
        if($_POST['info']['expire'] != 0 ){
            $_POST['info']['expire'] = strtotime($_POST['info']['expire']);
        }
        
        $d = M("Member");
        if($row=$d->create($_POST['info'])){
            if($d->save()){
                write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 1 , "修改用户uid:{$_POST['info']['uid']}成功" );
                return array('status'=>1 , 'message'=>'修改成功');
            }else{
                write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 0 , "修改用户uid:{$_POST['info']['uid']}失败" );
                return array('status'=>0 , 'message'=>'服务器繁忙请稍后');
            }
        }else{
            write_action_log($d->getLastSql() , getModuleAction() , $this->username , get_client_ip() , 0 , "数据创建失败" );
            return array('status'=>0 , 'message'=>'数据创建失败');
        }
    }   
    //修改状态
    public function doStatus($data = array() ){
        $d = M("Ad");
        $num = $d->where("id = '{$data['id']}'")->save(array('status'=>$data['status']));
        $sql = $d->getLastSql() ;
        if($num >=1 ){
            write_action_log($sql, getModuleAction() , $this->username , get_client_ip() , 1 , "修改广告id:{$data['id']}状态成功" );
            return array('status'=>1 , 'message'=>'修改成功');
        }
        write_action_log($sql, getModuleAction() , $this->username , get_client_ip() , 0 , "修改广告id:{$data['id']}状态失败" );
            return array('status'=>0 , 'message'=>'修改失败你可能没有修改数据');
    }
    //上传图片
    public function upload_ad_pic(){
            import('ORG.Net.UploadFile');
            $upload = new UploadFile();// 实例化上传类
            $upload->maxSize  = 3145728 ;// 设置附件上传大小
            $upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            $upload->savePath =  './Data/Upload/Ad/';// 设置附件上传目录
            $upload->autoSub = true;//使用子目录保存上传文件
            $upload->subType = 'date';//使用日期模式创建子目录
            $upload->dateFormat = 'Ymd';//设置子目录日期格式
            if(!$upload->upload()) {// 上传错误提示错误信息
                return array('status' => 0 , 'message'=> $upload->getErrorMsg());
            }else{// 上传成功 获取上传文件信息
                $info =  $upload->getUploadFileInfo();
            }
            return array('status'=>1 , 'message'=>'success' , 'pic'=>$info[0]['savename'] ) ;
            
    }
    //删除广告
    public function del($data = array() ){
        $info = M("Ad")->where("id={$data['id']}")->find();
        if(!$info){
            return array('status'=> 0 ,'message'=>'参数错误') ;
        }
        $num = M("Ad")->where("id={$data['id']}")->delete(); 
        $sql = M("Ad")->getLastSql();

        if($num){
            
            write_action_log($sql, getModuleAction(),$this->username,get_client_ip(),1,"删除广告--{$info['name']}--成功");
            return array('status'=> 1 ,'message'=>'操作成功') ;
        }else{
            write_action_log($sql, getModuleAction(),$this->username,get_client_ip(),0,"删除广告--{$info['name']}--失败");
            return array('status'=> 0 ,'message'=>'网络繁忙请稍后') ;
        }
    }
    
    public function queryMemberCount($p,$per_page = 100, $where = array()){
        if($p <=0 ){
            $p = 1 ;
        }
        $getwhere = " where 1 = 1 " ;
        
        if(isset($where['begin_date']) && $where['begin_date'] && !$where['end_date']){
            $begin_date = strtotime($where['begin_date']);
            $getwhere.=" AND a.regdate >='{$begin_date}' " ;
        }
        if(isset($where['end_date']) && $where['end_date'] && !$where['begin_date']){
            $end_date = strtotime($where['end_date']);
            $getwhere.=" AND a.regdate <='{$end_date}' " ;
        }
        if($where['end_date'] && $where['begin_date']){
            $begin_date = strtotime($where['begin_date']);
            $end_date = strtotime($where['end_date']);
            $getwhere.=" AND a.regdate <='{$end_date}' && a.regdate >='{$begin_date}' " ;
        }
      
        if( in_array($where['status'] , array('1', '0' ) ) ){
            $getwhere.=" AND a.status = '{$where['status']}' ";
        }
        if( in_array($where['sex'] , array('1', '2' ) ) ){
            $getwhere.=" AND a.sex = '{$where['sex']}' ";
        }
        $groupBy = "group by FROM_UNIXTIME(regdate , '%Y-%m-%d' )";
        $dateField = "FROM_UNIXTIME(regdate , '%Y-%m-%d' ) as date";
        if($where['count_type'] == 2 ){
            $groupBy = "group by FROM_UNIXTIME(regdate , '%Y-%m' )";
            $dateField = "FROM_UNIXTIME(regdate , '%Y-%m' ) as date";
        }
        import('Library.Page' , APP_PATH);
        $limit = ($p-1)*$per_page;
        $limit.=",{$per_page}";
        $sql_count = "select count(*) as cc from ({$dateField} , count(*) as c  from ".C("DB_PREFIX")."member as a   {$getwhere} {$groupBy} order by regdate desc ) bb " ;
        $count_data = M()->query($sql_count);
        $total = $count_data[0]['cc'];

        $page = new Page($total,$per_page);
        $page_string =  $page->show();
        $sql_list = "select {$dateField} , count(*) as c  from ".C("DB_PREFIX")."member as a   {$getwhere} {$groupBy} order by regdate desc limit {$limit}" ;
       // echo $sql_list;
        $count_data = M()->query($sql_list);
        $data = array(
           'list'=>array('list'=>$count_data,'page_string'=>$page_string)  ,   
        );
        return $data ;
    }  
}
